import config from 'config';

function getStorage(key) {
	return uni.getStorageSync(`$${config.clientId}_${key}`);
}

function setStorage(options, value) {
	if (typeof options === 'string')
		return uni.setStorageSync(`$${config.clientId}_${options}`, value);
	if (options.key) options.key = `$${config.clientId}_${options.key}`;
	uni.setStorage(options);
}

function removeStorage(options) {
	if (typeof options === 'string')
		return uni.removeStorageSync(`$${config.clientId}_${options}`);
	if (options.key) options.key = `$${config.clientId}_${options.key}`;
	uni.removeStorage(options);
}

function queryStringToObject(str) {
	var obj = {}
	var splitStringArray = str.substring(str.indexOf("?") + 1).split('&');
	splitStringArray.forEach(item => {
		if (item) {
			var kv = item.split('=');
			obj[kv[0]] = kv[1];
		}
	});
	return obj;
}

function objectToQueryString(obj) {
	var queryString = '?';
	for (let key in obj) {
		queryString += `${key}=${obj[key]}&`;
	}
	queryString = queryString.replace(/&$/, '');
	if (queryString === '?') {
		queryString = '';
	}
	return queryString;
}

function queryStringRemoveParams(url, names) {
	if (typeof(names) === 'string') {
		names = [names];
	}
	var obj = queryStringToObject(url);
	for (var i = 0; i < names.length; i++) {
		delete obj[names[i]];
	}
	return objectToQueryString(obj);
}

function toErrorPage(code, message) {
	uni.redirectTo({
		url: `/pages/error/error?code=${code}&message=${message}`
	});
}

function toLinkPage(link, title) {
	if (!link) return
	if (!title) title = config.appName
	if (link.startsWith('/')) {
		uni.navigateTo({
			url: link
		});
	} else {
		uni.navigateTo({
			url: `/pages/webview/webview?link=${link}&title=${title}`
		});
	}
}

function navigateBack() {
	var pages = getCurrentPages();
	if (pages.length > 1) {
		uni.navigateBack();
	} else {
		uni.reLaunch({
			url: '/'
		});
	}
}

//表单序列化
export const serialize = data => {
	let list = [];
	Object.keys(data).forEach(ele => {
		list.push(`${ele}=${data[ele]}`)
	})
	return list.join('&');
};

function facebookHandle(pixel) {
	!function(f,b,e,v,n,t,s)
	{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
		n.callMethod.apply(n,arguments):n.queue.push(arguments)};
		if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
		n.queue=[];t=b.createElement(e);t.async=!0;
		t.src=v;s=b.getElementsByTagName(e)[0];
		s.parentNode.insertBefore(t,s)}(window, document,'script',
		'https://connect.facebook.net/en_US/fbevents.js');

	fbq('init', pixel);
	fbq('track', 'PageView');
}

function facebookMessageHandle() {
	window.fbAsyncInit = function() {
		FB.init({
			xfbml            : true,
			version          : 'v13.0'
		});
	};

	(function(d, s, id) {
		var js, fjs = d.getElementsByTagName(s)[0];
		if (d.getElementById(id)) return;
		js = d.createElement(s); js.id = id;
		js.src = 'https://connect.facebook.net/zh_TW/sdk/xfbml.customerchat.js';
		fjs.parentNode.insertBefore(js, fjs);
	}(document, 'script', 'facebook-jssdk'));
}

function kSort(params) {
	let keys = Object.keys(params).sort()
	let newParams = {}
	keys.forEach(key => {
		newParams[key] = params[key]
	})
	return newParams
}

export default {
	getStorage,
	setStorage,
	removeStorage,
	queryStringToObject,
	objectToQueryString,
	queryStringRemoveParams,
	toErrorPage,
	toLinkPage,
	navigateBack,
	serialize,
	facebookMessageHandle,
	facebookHandle,
	kSort
}
